package com.carboy.launch.activity.setting;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.carboy.launch.R;
import com.carboy.launch.activity.column.BaseActivity;

/**
 * 设置--状态信息Activity
 */
public class SStateMessageActivity extends BaseActivity implements
		OnClickListener {

	// 当前上下文
	private Context mContext;

	// ================== 控件View =================
	private ImageView is_network_igview; // wifi状态
	private TextView is_enumber_tv = null; // 电量
	private ImageView assm_break_igview; // 返回键
	private TextView assm_bstate_tv; // 电池状态
	private TextView assm_bnumber_tv; // 电量
	private TextView assm_wmacaddress_tv; // Mac地址
	private TextView assm_btaddress_tv; // 蓝牙地址
	private TextView assm_ipaddress_tv; // ip地址
	private TextView assm_snumber_tv; // 序列号
	private TextView assm_bstrap_tv; // 开机时间
	// ================== 其他对象 =================
	public static BluetoothAdapter btAda; // 蓝牙适配器

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_state_message);
		mContext = SStateMessageActivity.this;

		initViews();
		initStatusBar();
		initValues();
		initListeners();
	}

	/**
	 * 初始化控件
	 */
	private void initViews() {
		assm_break_igview = (ImageView) this
				.findViewById(R.id.assm_break_igview); // 返回键
		assm_bstate_tv = (TextView) this.findViewById(R.id.assm_bstate_tv); // 电池状态
		assm_bnumber_tv = (TextView) this.findViewById(R.id.assm_bnumber_tv); // 电量
		assm_wmacaddress_tv = (TextView) this
				.findViewById(R.id.assm_wmacaddress_tv); // Mac地址
		assm_btaddress_tv = (TextView) this
				.findViewById(R.id.assm_btaddress_tv); // 蓝牙地址
		assm_ipaddress_tv = (TextView) this
				.findViewById(R.id.assm_ipaddress_tv); // ip地址
		assm_snumber_tv = (TextView) this.findViewById(R.id.assm_snumber_tv); // 序列号
		assm_bstrap_tv = (TextView) this.findViewById(R.id.assm_bstrap_tv); // 开机时间

		is_network_igview = (ImageView) this
				.findViewById(R.id.is_network_igview); // wifi状态
	}

	/**
	 * 初始化参数
	 */
	private void initValues() {
		assm_wmacaddress_tv.setText(getWLANMacAddress());
		// 实例蓝牙适配器
		btAda = BluetoothAdapter.getDefaultAdapter();
		switch (btAda.getState()) {
		case BluetoothAdapter.STATE_OFF: // 已关闭
			assm_btaddress_tv.setText("不可用");
			break;
		case BluetoothAdapter.STATE_ON: // 已打开
			assm_btaddress_tv.setText(btAda.getAddress());
			break;
		default:
			assm_btaddress_tv.setText("不可用");
			break;
		}
		TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		assm_snumber_tv.setText(TelephonyMgr.getDeviceId());
		// String serial = android.os.Build.SERIAL;
		// assm_snumber_tv.setText(serial);
		setTimeParam();
	}

	/**
	 * 初始化事件
	 */
	private void initListeners() {
		assm_break_igview.setOnClickListener(this);
	}

	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.assm_break_igview: // 返回键
			SStateMessageActivity.this.finish();
			break;
		}
	}

	/**
	 * 重写返回键
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			SStateMessageActivity.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// Activity被回收,则保存数据
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// 切屏触发
	}

	// ============================ 状态信息 ==================================
	private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			/*
			 * 如果捕捉到的action是ACTION_BATTERY_CHANGED， 就运行onBatteryInfoReceiver()
			 */
			if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
				int intLevel = intent.getIntExtra("level", 0);
				int intScale = intent.getIntExtra("scale", 100);
				assm_bnumber_tv.setText(intLevel + "%");
				is_enumber_tv.setText(intLevel + "%");
				// String BatteryV = "当前电压为：" + intent.getIntExtra("voltage",
				// 0);
				// String BatteryT = "当前温度为：" +
				// intent.getIntExtra("temperature", 0);
				switch (intent.getIntExtra("status",
						BatteryManager.BATTERY_STATUS_UNKNOWN)) {
				case BatteryManager.BATTERY_STATUS_CHARGING:
					assm_bstate_tv.setText(getResources().getString(R.string.battery_status_charging));
					break;
				case BatteryManager.BATTERY_STATUS_DISCHARGING:
					assm_bstate_tv.setText(getResources().getString(R.string.battery_status_charging));
					break;
				case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
					assm_bstate_tv.setText(getResources().getString(R.string.battery_status_not_charging));
					break;
				case BatteryManager.BATTERY_STATUS_FULL:
					assm_bstate_tv.setText(getResources().getString(R.string.battery_status_full));
					break;
				case BatteryManager.BATTERY_STATUS_UNKNOWN:
					assm_bstate_tv.setText(getResources().getString(R.string.battery_status_unknow));
					break;
				}
				switch (intent.getIntExtra("plugged",
						BatteryManager.BATTERY_PLUGGED_AC)) {
				case BatteryManager.BATTERY_PLUGGED_AC:
					assm_bstate_tv.setText(getResources().getString(R.string.battery_plugged_ac));
					break;
				case BatteryManager.BATTERY_PLUGGED_USB:
					assm_bstate_tv.setText(getResources().getString(R.string.battery_plugged_usb));
					break;
				}
				/*
				 * switch (intent.getIntExtra("health",BatteryManager.
				 * BATTERY_HEALTH_UNKNOWN)) { case
				 * BatteryManager.BATTERY_HEALTH_UNKNOWN:
				 * assm_bstate_tv.setText("未知错误"); break; case
				 * BatteryManager.BATTERY_HEALTH_GOOD:
				 * assm_bstate_tv.setText("状态良好"); break; case
				 * BatteryManager.BATTERY_HEALTH_DEAD:
				 * assm_bstate_tv.setText("电池没有电"); break; case
				 * BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
				 * assm_bstate_tv.setText("电池电压过高"); break; case
				 * BatteryManager.BATTERY_HEALTH_OVERHEAT:
				 * assm_bstate_tv.setText("电池过热"); break; }
				 */
			}
		}
	};

	// 监听动作
	private BroadcastReceiver searchDevices = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
				switch (btAda.getState()) {
				case BluetoothAdapter.STATE_OFF: // 已关闭
					assm_btaddress_tv.setText(getResources().getString(R.string.bt_state));
					break;
				case BluetoothAdapter.STATE_ON: // 已打开
					assm_btaddress_tv.setText(btAda.getAddress());
					break;
				case BluetoothAdapter.STATE_TURNING_OFF:
					// assm_btaddress_tv.setText("关闭中");
					break;
				case BluetoothAdapter.STATE_TURNING_ON:
					// assm_btaddress_tv.setText("打开中");
					break;
				default:
					assm_btaddress_tv.setText(getResources().getString(R.string.bt_state));
					break;
				}
			}
		}
	};

	/**
	 * 获取WLAN_Mac地址
	 */
	private String getWLANMacAddress() {
		String macSerial = null;
		String str = "";
		try {
			Process pp = Runtime.getRuntime().exec(
					"cat /sys/class/net/wlan0/address ");
			InputStreamReader ir = new InputStreamReader(pp.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			for (; null != str;) {
				str = input.readLine();
				if (str != null) {
					macSerial = str.trim();// 去空格
					break;
				}
			}
		} catch (IOException ex) {
			// 赋予默认值
			return getResources().getString(R.string.bt_state);
		}
		// 存在地址并且,不等于null
		if (macSerial != null && macSerial.trim().length() != 0)
			return macSerial;
		else
			return getResources().getString(R.string.bt_state);
	}

	// ========================== 网络状态 ================================
	/**
	 * 网络状态改变广播监听
	 */
	private BroadcastReceiver mNetWorkStateChanageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
				try {
					ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo info = connectivityManager
							.getActiveNetworkInfo();
					if (info != null && info.isAvailable()) {
						String name = info.getTypeName();
						if ("WIFI".equals(name)) {
							is_network_igview.setVisibility(View.VISIBLE);
						} else {
							is_network_igview.setVisibility(View.GONE);
						}
					} else {
						is_network_igview.setVisibility(View.GONE);
					}
				} catch (Exception e) {
				}
				assm_ipaddress_tv.setText(getAPNType(context));
			}
		}
	};

	/**
	 * 1.无网络（这种状态可能是因为手机停机，网络没有开启，信号不好等原因） 2.使用WIFI上网 3.CMWAP（中国移动代理） 4.CMNET上网
	 */
	public String getAPNType(Context context) {
		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo == null) {
			return getResources().getString(R.string.bt_state);
		}
		return getPhoneIp();
	}

	public String getPhoneIp() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& inetAddress instanceof Inet4Address) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (Exception e) {
			return getResources().getString(R.string.bt_state);
		}
		return getResources().getString(R.string.bt_state);
	}

	// ========================== 定时器 ================================
	/** 设置定时器参数 */
	private void setTimeParam() {
		sBootTimer = new Timer(); // 每次重新new 防止被取消
		// 重新生成定时器 防止出现TimerTask is scheduled already 所以同一个定时器任务只能被放置一次
		sBootTask = new TimerTask() {
			@Override
			public void run() {
				// 需要做的事:发送消息
				Message message = new Message();
				message.what = 1;
				sBootHandler.sendMessage(message);
			}
		};
		sBootTimer.schedule(sBootTask, 0, 990); // 开启定时器
	}

	Timer sBootTimer; // 定时器
	TimerTask sBootTask; // 定时器任务栈
	Handler sBootHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				long ms = SystemClock.elapsedRealtime();// 毫秒数
				SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");// 初始化Formatter的转换格式。
				formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
				String hms = formatter.format(ms);
				assm_bstrap_tv.setText(((ms / 1000) / 3600) + ":" + hms);
			}
			super.handleMessage(msg);
		};
	};

}
